package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 带数据向页面响应
 */
//@ResponseBody 1.阻止页面跳转，实现页面写入数据  2.将对象转换成json格式数据z
@RestController//等同于@Controller+@ResponseBody联合使用
@RequestMapping("json")
public class JsonController {

    @RequestMapping("/test1")
    public void test1(HttpServletResponse response)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("合肥");
    }

    @RequestMapping(value = "/test2",produces = "text/html;charset=utf-8")
    public String test2()throws Exception{
        return "武汉";
    }

    @RequestMapping("/test3")
    public void test3(HttpServletResponse resp)throws Exception{
        User user = new User();
        user.setUsername("zhangsan");
        user.setAge(18);

        String s = new ObjectMapper().writeValueAsString(user);
        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(s);
    }

    @RequestMapping("/test4")
    public User test4(HttpServletResponse resp)throws Exception {
        User user = new User();
        user.setUsername("lisi");
        user.setAge(28);
        return user;
    }

    @RequestMapping("/test5")
    public Map test5(HttpServletResponse resp)throws Exception {
        User user = new User();
        user.setUsername("lisi");
        user.setAge(28);

        HashMap hm = new HashMap();
        hm.put("user",user);
        return hm;
    }
}
